package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.adapter.IBaseAdapter;
import com.jml.zlhq.app.adapter.JinbiHistoryAdapter;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;

public class JinbiHistoryActivity extends BaseActivity {
	private PullToRefreshListView mPullToRefreshView;
	private ListView listView;
	private IBaseAdapter adapter;
	private List<JSONObject> listItems = new ArrayList<JSONObject>();
	public static boolean freshPage;
	private Map<String,String> conditionMap;
	private String url;
	private String title;
	private int type = 1;
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter.notifyDataSetChanged();
				mPullToRefreshView.onRefreshComplete();
				if(pageEnd)mPullToRefreshView.setMode(Mode.PULL_FROM_START);
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tuijian_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.INVISIBLE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("金币记录");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView centerChosed = (TextView) findViewById(R.id.content_header_center_text2);
		centerChosed.setVisibility(View.GONE);
		
		try {
			type = getIntent().getExtras().getInt("type");
			title = getIntent().getExtras().getString("title");
			centerText.setText(title);
			url = getIntent().getExtras().getString("url");
		} catch (Exception e) {
			e.printStackTrace();
		}
				
		mPullToRefreshView = (PullToRefreshListView) findViewById(R.id.tuijian_listview);
		mPullToRefreshView.setMode(Mode.DISABLED);
		mPullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if(PullToRefreshBase.Mode.PULL_FROM_START == mPullToRefreshView.getCurrentMode()){
					String label = DateUtils.formatDateTime(appContext,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
					mPullToRefreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					clearData();
					loadData(null);
				}else if(PullToRefreshBase.Mode.PULL_FROM_END == mPullToRefreshView.getCurrentMode()){
					if(urlParam==null)urlParam = new HashMap<String,String>();
					pageIndex++;
					urlParam.put("pageNo", String.valueOf(pageIndex));
					loadData(urlParam);
				}
			}
		});
		listView = mPullToRefreshView.getRefreshableView();
		listView.setDividerHeight(0);
		adapter = new JinbiHistoryAdapter(activity, listItems, type);
		listView.setAdapter(adapter);
		
		freshPage = false;
		loadData(null);
	}
	
	@Override
	public void onResume() {
		pageFresh = freshPage;
		super.onResume();
		freshPage = false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==4&&resultCode==Activity.RESULT_OK&&null!=data){
			conditionMap = (Map<String,String>) data.getSerializableExtra("data");
			if(urlParam==null)urlParam = new HashMap<String,String>();
			urlParam.clear();
			urlParam.put("page", String.valueOf(1));
			urlParam.putAll(conditionMap);
			listItems.clear();
			loadData(urlParam);
		}
	}

	@Override
	public void loadData(Map<String, String> param) {
		if(param==null)param = new HashMap<String, String>();
		param.put("page", String.valueOf(pageIndex));
		param.put("auth_token", appContext.getLoginUid());
		HttpService.getByText(url, param, new TextHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
				try {
					if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
					JSONObject result = new JSONObject(resultStr);
					if(result.getInt("status")==0){
						JSONArray data = result.getJSONArray("data");
						for (int i = 0; data!=null && i < data.length(); i++) {
							listItems.add(data.getJSONObject(i));
						}
						if(data==null||data.length()<=0){
							pageEnd = true;
							adapter.setPageEnd(pageEnd);
						}
					}else{
						if(pageIndex>0)pageIndex--;
					}
					mHandler.sendEmptyMessage(1);
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				UIUtil.ToastMessage(activity, "抱歉，访问失败");
			}
		});
//		listItems.add(new JSONObject());
//		adapter.notifyDataSetChanged();
//		mPullToRefreshView.onRefreshComplete();
	}

	@Override
	public void clearData() {
		pageEnd = false;
		if(urlParam==null)urlParam = new HashMap<String,String>();
		pageIndex = 1;
		urlParam.put("page", String.valueOf(pageIndex));
		adapter.setPageEnd(pageEnd);
		mPullToRefreshView.setMode(Mode.BOTH);
		listItems.clear();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		/*case R.id.content_header_right_lay:
			Bundle data = new Bundle();
			data.putString("url", URLs.MAIN_FAXIAN_CONDITION);
			data.putSerializable("condition", (Serializable) conditionMap);
			UIUtil.openActivity(this, ConditionActivity.class, data, 4);
			break;*/
		default:
			break;
		}
	}

}
